﻿/*
* 创建者：LIYINFAI
* 创建时间：2023/10/15 11:40:00
* 描述：
* --------------------------------------
* 修改说明：
* --------------------------------------
*/
using CommonLibrary.Forms;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

namespace CommonLibrary
{
    /// <summary>
    /// 氦检仪管理窗体
    /// </summary>
    public partial class FormHelium : HWFrmWithTitle
    {
        private bool mIsFirstTimeSelected = true;
        private int mTcpLastSelectedRowIndex = -1;
        private int mSerialLastSelectedRowIndex = -1;
        /// <summary>
        /// 构造函数
        /// </summary>
        public FormHelium()
        {
            InitializeComponent();
        }
        private void FormHelium_Load(object sender, EventArgs e)
        {
            InitHeliumColumns();
            LoadHeliumConfig();
            this.labelStart.Select();
        }
        private void LoadHeliumConfig()
        {
            this.mIsFirstTimeSelected = true;
            this.mSerialLastSelectedRowIndex = -1;
            this.mTcpLastSelectedRowIndex = -1;
            this.dataGridViewSerial.Rows.Clear();
            this.dataGridViewTcp.Rows.Clear();
            this.dataGridViewModules.Rows.Clear();
            HeliumConfig heliumConfig = HeliumConfig.Instance();
            this.textBoxBackgroundLeakRate.Text = CommonHelper.GetScientificNotation(heliumConfig.BackgroundRate);
            this.textBoxPressMax.Text = CommonHelper.GetScientificNotation(heliumConfig.LeakPressMax);
            this.textBoxPressMin.Text = CommonHelper.GetScientificNotation(heliumConfig.LeakPressMin);
            this.textBoxLeakRateMax.Text = CommonHelper.GetScientificNotation(heliumConfig.LeakRateMax);
            this.textBoxLeakRateMin.Text = CommonHelper.GetScientificNotation(heliumConfig.LeakRateMin);
            var tcpConfigs = HeliumHelper.GetTcpHeliumConfig();
            if (tcpConfigs != null && tcpConfigs.Count > 0)
            {
                foreach (var t in tcpConfigs)
                {
                    var index = this.dataGridViewTcp.Rows.Add(1);
                    DataGridViewRow newRow = this.dataGridViewTcp.Rows[index];
                    newRow.Cells["Name"].Value = t.Remark;
                    newRow.Cells["TcpIP"].Value = t.ServerIP;
                    newRow.Cells["TcpPort"].Value = t.ServerPort.ToString();
                    newRow.Cells["Status"].Value = t.StatusAddress;
                    newRow.Tag = t;
                }
            }
            var comConfigs = HeliumHelper.GetComHeliumConfig();
            if (comConfigs != null && comConfigs.Count > 0)
            {
                foreach (var t in comConfigs)
                {
                    var index = this.dataGridViewSerial.Rows.Add(1);
                    DataGridViewRow newRow = this.dataGridViewSerial.Rows[index];
                    newRow.Cells["Name"].Value = t.Remark;
                    newRow.Cells["PortName"].Value = !string.IsNullOrWhiteSpace(t.PortName) && PortNames.Contains(t.PortName) ? t.PortName : PortNames[0];
                    newRow.Cells["Parity"].Value = t.Parity.ToString();
                    newRow.Cells["DataBit"].Value = t.DataBits.ToString();
                    newRow.Cells["StopBit"].Value = t.StopBits.ToString();
                    newRow.Cells["BaudRate"].Value = t.BaudRate.ToString();
                    newRow.Cells["Status"].Value = t.StatusAddress;
                    newRow.Tag = t;
                }
            }
            this.dataGridViewTcp.Rows[0].Cells[0].Selected = true;
        }
        private string[] PortNames = SerialPort.GetPortNames();
        DataGridViewComboBoxColumn portNameSerialColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn baudRateSerialColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn paritySerialColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn dataBitSerialColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn stopBitSerialColumn = new DataGridViewComboBoxColumn();
        private void InitHeliumColumns()
        {
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "Name", "名称");
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "TcpIP", "IP");
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "TcpPort", "端口");
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "Status", "氦检设备状态地址");
            this.dataGridViewTcp.DoubleBufferedDataGirdView(true);
            this.dataGridViewTcp.InitStyle();
            CommonHelper.CreateTextGridColumn(this.dataGridViewSerial, "Name", "名称");
            CommonHelper.InitComboGridColumn(portNameSerialColumn, "PortName", "串口", PortNames);
            CommonHelper.InitComboGridColumn(baudRateSerialColumn, "BaudRate", "波特率", new string[] { "2400", "4800", "9600", "14400", "19200", "115200" });
            CommonHelper.InitComboGridColumn(paritySerialColumn, "Parity", "校验位", new string[] { "0", "1", "2", "3", "4" });
            CommonHelper.InitComboGridColumn(dataBitSerialColumn, "DataBit", "数据位", new string[] { "5", "6", "7", "8" });
            CommonHelper.InitComboGridColumn(stopBitSerialColumn, "StopBit", "停止位", new string[] { "0", "1", "2", "3" });
            this.dataGridViewSerial.Columns.Add(portNameSerialColumn);
            this.dataGridViewSerial.Columns.Add(baudRateSerialColumn);
            this.dataGridViewSerial.Columns.Add(paritySerialColumn);
            this.dataGridViewSerial.Columns.Add(dataBitSerialColumn);
            this.dataGridViewSerial.Columns.Add(stopBitSerialColumn);
            CommonHelper.CreateTextGridColumn(this.dataGridViewSerial, "Status", "氦检设备状态地址");
            this.dataGridViewSerial.DoubleBufferedDataGirdView(true);
            this.dataGridViewSerial.InitStyle();
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "remarkModuleColumn", "备注");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "triggerBackgroudModuleColumn", "触发氦检仓背景检测地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "backgroudJudgeModuleColumn", "氦检仓背景判断反馈地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "triggerHeliumModuleColumn", "触发氦检仓氦检测试地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "heliumJudgeModuleColumn", "氦检仓氦检判断反馈地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "leakValueModuleColumn", "漏率地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "pressValueModuleColumn", "检漏口压力地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "heliumTimesModuleColumn", "氦检时间地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "heliumResultModuleColumn", "氦检结果地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "readPermitModuleColumn", "允许读取地址");
            this.dataGridViewModules.DoubleBufferedDataGirdView(true);
            this.dataGridViewModules.InitStyle();
        }
        private void buttonSave_Click(object sender, EventArgs e)
        {
            CommonHelper.ShowWaiting(this, "数据保存中，请稍候......");
            if (GlobalStatus.APP == EAppStatus.RUN)
            {
                HWMessageBox.Show(this, "设备运行中，不允许修改参数");
                CommonHelper.CloseWaiting();
                return;
            }
            try
            {
                SaveModules();
                bool isValidTcp = true, isValidSerial = true, isValidOther = true;
                string barcodePrev = string.Empty;
                List<HeliumTcpParam> tcpList = new List<HeliumTcpParam>();
                List<HeliumComParam> comList = new List<HeliumComParam>();
                if (this.dataGridViewTcp.Rows != null && this.dataGridViewTcp.Rows.Count > 0)
                {
                    int rowIndex = 0;
                    foreach (DataGridViewRow row in this.dataGridViewTcp.Rows)
                    {
                        var name = CommonHelper.GetCellStringValue(row, "Name");
                        if (!string.IsNullOrWhiteSpace(name))
                        {
                            var ip = CommonHelper.GetCellStringValue(row, "TcpIP");
                            var port = CommonHelper.GetCellStringValue(row, "TcpPort");
                            var status = CommonHelper.GetCellStringValue(row, "Status");
                            IPAddress ipValue = null;
                            if (!IPAddress.TryParse(ip, out ipValue))
                            {
                                HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的IP有误");
                                isValidTcp = false;
                                break;
                            }
                            int portValue = 9004;
                            if (!int.TryParse(port, out portValue))
                            {
                                HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的端口有误");
                                isValidTcp = false;
                                break;
                            }
                            if (string.IsNullOrWhiteSpace(status))
                            {
                                HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的地址有误");
                                isValidTcp = false;
                                break;
                            }
                            var tcpParam = new HeliumTcpParam()
                            {
                                Remark = name,
                                ServerIP = ipValue.ToString(),
                                ServerPort = portValue,
                                StatusAddress = status,
                            };
                            if (row.Tag != null && row.Tag is HeliumTcpParam)
                            {
                                tcpParam.PLCEntities.Clear();
                                var temp = (HeliumTcpParam)row.Tag;
                                foreach (var t in temp.PLCEntities)
                                {
                                    tcpParam.PLCEntities.Add(t);
                                }
                            }
                            tcpList.Add(tcpParam);
                        }
                        rowIndex++;
                    }
                }
                if (isValidTcp)
                {
                    if (this.dataGridViewSerial.Rows != null && this.dataGridViewSerial.Rows.Count > 0)
                    {
                        int rowIndex = 0;
                        foreach (DataGridViewRow row in this.dataGridViewSerial.Rows)
                        {
                            var name = CommonHelper.GetCellStringValue(row, "Name");
                            if (!string.IsNullOrWhiteSpace(name))
                            {
                                var portName = CommonHelper.GetCellStringValue(row, "PortName");
                                var baudRate = CommonHelper.GetCellStringValue(row, "BaudRate");
                                var parity = CommonHelper.GetCellStringValue(row, "Parity");
                                var dataBit = CommonHelper.GetCellStringValue(row, "DataBit");
                                var stopBit = CommonHelper.GetCellStringValue(row, "StopBit");
                                var status = CommonHelper.GetCellStringValue(row, "Status");
                                if (string.IsNullOrWhiteSpace(portName))
                                {
                                    HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的串口有误");
                                    isValidSerial = false;
                                    break;
                                }
                                int baudRateValue = int.Parse(baudRate);
                                int parityValue = int.Parse(parity);
                                int dataBitValue = int.Parse(dataBit);
                                int stopBitValue = int.Parse(stopBit);
                                if (string.IsNullOrWhiteSpace(status))
                                {
                                    HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的地址有误");
                                    isValidSerial = false;
                                    break;
                                }
                                var comParam = new HeliumComParam()
                                {
                                    Remark = name,
                                    BaudRate = baudRateValue,
                                    Parity = parityValue,
                                    DataBits = dataBitValue,
                                    PortName = portName,
                                    StopBits = stopBitValue,
                                    StatusAddress = status,
                                };
                                if (row.Tag != null && row.Tag is HeliumComParam)
                                {
                                    comParam.PLCEntities.Clear();
                                    var temp = (HeliumComParam)row.Tag;
                                    foreach (var t in temp.PLCEntities)
                                    {
                                        comParam.PLCEntities.Add(t);
                                    }
                                }
                                comList.Add(comParam);
                            }
                            rowIndex++;
                        }
                    }
                }
                float backgroundLeakRateFloat = 1.00E-005f, pressMaxFloat = 600f, pressMinFloat = 0f, rateMaxFloat = 9.99E-007f, rateMinFloat = 1.00E-020f;
                if (isValidTcp && isValidSerial)
                {
                    if (!float.TryParse(this.textBoxBackgroundLeakRate.Text, out backgroundLeakRateFloat))
                    {
                        isValidOther = false;
                        HWMessageBox.Show(this, "背景漏率有误");
                    }
                    else if (!float.TryParse(this.textBoxPressMax.Text, out pressMaxFloat))
                    {
                        isValidOther = false;
                        HWMessageBox.Show(this, "压力上限有误");
                    }
                    else if (!float.TryParse(this.textBoxPressMin.Text, out pressMinFloat))
                    {
                        isValidOther = false;
                        HWMessageBox.Show(this, "压力下限有误");
                    }
                    else if (!float.TryParse(this.textBoxLeakRateMax.Text, out rateMaxFloat))
                    {
                        isValidOther = false;
                        HWMessageBox.Show(this, "漏率上限有误");
                    }
                    else if (!float.TryParse(this.textBoxLeakRateMin.Text, out rateMinFloat))
                    {
                        isValidOther = false;
                        HWMessageBox.Show(this, "漏率下限有误");
                    }
                }
                if (isValidTcp && isValidSerial && isValidOther)
                {
                    HeliumHelper.SaveTcpHeliumConfig(tcpList);
                    HeliumHelper.SaveComHeliumConfig(comList);
                    HeliumConfig heliumConfig = HeliumConfig.Instance();
                    heliumConfig.BackgroundRate = backgroundLeakRateFloat;
                    heliumConfig.LeakPressMax = pressMaxFloat;
                    heliumConfig.LeakPressMin = pressMinFloat;
                    heliumConfig.LeakRateMax = rateMaxFloat;
                    heliumConfig.LeakRateMin = rateMinFloat;
                    heliumConfig.Save();
                    LogHelper.Info($"修改氦检仪配置\r\n{CommonHelper.GetJsonString(heliumConfig)}\r\n{CommonHelper.GetJsonString(tcpList)}\r\n{CommonHelper.GetJsonString(comList)}");
                    APPInstance.ResetHelpers();
                    this.DialogResult = DialogResult.OK;
                    HWMessageBox.Show(this, "保存成功");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                HWMessageBox.Show(this, $"发生异常：{ex.Message}");
            }
            CommonHelper.CloseWaiting();
        }
        private void dataGridViewTcp_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
        }
        private void dataGridViewTcp_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
        }
        private void dataGridViewSerial_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex.Equals(this.dataGridViewSerial.Columns.IndexOf(portNameSerialColumn))
                || e.ColumnIndex.Equals(this.dataGridViewSerial.Columns.IndexOf(paritySerialColumn))
                || e.ColumnIndex.Equals(this.dataGridViewSerial.Columns.IndexOf(baudRateSerialColumn))
                || e.ColumnIndex.Equals(this.dataGridViewSerial.Columns.IndexOf(dataBitSerialColumn))
                || e.ColumnIndex.Equals(this.dataGridViewSerial.Columns.IndexOf(stopBitSerialColumn)))
            {
                SendKeys.Send("{F4}");
            }
        }
        private void dataGridViewSerial_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            var portNameCell = e.Row.Cells["PortName"] as DataGridViewComboBoxCell;
            if (portNameCell != null && PortNames != null && PortNames.Length > 0)
            {
                portNameCell.Value = PortNames[0];
            }
            var baudRateCell = e.Row.Cells["BaudRate"] as DataGridViewComboBoxCell;
            if (baudRateCell != null)
            {
                baudRateCell.Value = "9600";
            }
            var parityCell = e.Row.Cells["Parity"] as DataGridViewComboBoxCell;
            if (parityCell != null)
            {
                parityCell.Value = "0";
            }
            var stopBitCell = e.Row.Cells["StopBit"] as DataGridViewComboBoxCell;
            if (stopBitCell != null)
            {
                stopBitCell.Value = "1";
            }
            var dataBitCell = e.Row.Cells["DataBit"] as DataGridViewComboBoxCell;
            if (dataBitCell != null)
            {
                dataBitCell.Value = "8";
            }
        }
        private void toolStripMenuItemRead_Click(object sender, EventArgs e)
        {
            CommonHelper.ShowWaiting(this, "功能触发中，请稍候......");
            var cells = this.dataGridViewTcp.SelectedCells;
            if (cells != null && cells.Count > 0)
            {
                var row = this.dataGridViewTcp.Rows[cells[0].RowIndex];
                var name = CommonHelper.GetCellStringValue(row, "Name");
                if (!string.IsNullOrWhiteSpace(name))
                {
                    var ip = CommonHelper.GetCellStringValue(row, "TcpIP");
                    var port = CommonHelper.GetCellStringValue(row, "TcpPort");
                    IPAddress ipValue = null;
                    if (!IPAddress.TryParse(ip, out ipValue))
                    {
                        HWMessageBox.Show(this, $"IP有误");
                    }
                    else
                    {
                        int portValue = 502;
                        if (!int.TryParse(port, out portValue))
                        {
                            HWMessageBox.Show(this, $"端口有误");
                        }
                        else
                        {
                            var helper = APPInstance.HELPERS != null ?
                                APPInstance.HELPERS.Find(v => v is HeliumHelper
                                && v.Name.Equals(name.ToString())
                                && v.CommunicationType == ECommunicationType.TCP) : null;
                            if (helper != null)
                            {
                                try
                                {
                                    string content = CommonHelper.RemoveEnterString((helper as HeliumHelper).ReadLeakRate());
                                    HWMessageBox.Show(this, $"结果：{content}");
                                }
                                catch (Exception ex)
                                {
                                    HWMessageBox.Show(this, $"发生异常：{ex.Message}");
                                }
                            }
                            else
                            {
                                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                                try
                                {
                                    socket.ReceiveTimeout = 1000;
                                    socket.ConnectAsync(ipValue, portValue).Wait(500);
                                    if (socket.Connected)
                                    {
                                        socket.Send(Encoding.UTF8.GetBytes("G1\r"));
                                        byte[] buffer = new byte[1024];
                                        int length = socket.Receive(buffer);
                                        if (length > 0)
                                        {
                                            string content = Encoding.UTF8.GetString(buffer.Take(length).ToArray());
                                            HWMessageBox.Show(this, $"结果：{content}");
                                        }
                                        else
                                        {
                                            HWMessageBox.Show(this, "通讯异常");
                                        }
                                    }
                                    else
                                    {
                                        HWMessageBox.Show(this, "无法建立连接");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    HWMessageBox.Show(this, $"发生异常：{ex.Message}");
                                }
                                finally
                                {
                                    if (socket != null && socket.Connected)
                                    {
                                        socket.Close();
                                        socket = null;
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    HWMessageBox.Show(this, "名称有误");
                }
            }
            else
            {
                HWMessageBox.Show(this, "请先选中记录");
            }
            CommonHelper.CloseWaiting();
        }
        private void toolStripMenuItemSerialRead_Click(object sender, EventArgs e)
        {
            CommonHelper.ShowWaiting(this, "功能触发中，请稍候......");
            var cells = this.dataGridViewSerial.SelectedCells;
            if (cells != null && cells.Count > 0)
            {
                var row = this.dataGridViewSerial.Rows[cells[0].RowIndex];
                var name = CommonHelper.GetCellStringValue(row, "Name");
                if (!string.IsNullOrWhiteSpace(name))
                {
                    var portName = CommonHelper.GetCellStringValue(row, "PortName");
                    var baudRate = CommonHelper.GetCellStringValue(row, "BaudRate");
                    var parity = CommonHelper.GetCellStringValue(row, "Parity");
                    var dataBit = CommonHelper.GetCellStringValue(row, "DataBit");
                    var stopBit = CommonHelper.GetCellStringValue(row, "StopBit");
                    if (string.IsNullOrWhiteSpace(portName))
                    {
                        HWMessageBox.Show(this, $"串口有误");
                    }
                    else
                    {
                        int baudRateValue = int.Parse(baudRate);
                        int parityValue = int.Parse(parity);
                        int dataBitValue = int.Parse(dataBit);
                        int stopBitValue = int.Parse(stopBit);
                        var helper = APPInstance.HELPERS != null ?
                            APPInstance.HELPERS.Find(v => v is HeliumHelper
                            && v.Name.Equals(name)
                            && v.CommunicationType == ECommunicationType.SERIAL
                            && v.IsConnected) : null;
                        if (helper != null)
                        {
                            try
                            {
                                string content = CommonHelper.RemoveEnterString((helper as HeliumHelper).ReadLeakRate());
                                HWMessageBox.Show(this, $"结果：{content}");
                            }
                            catch (Exception ex)
                            {
                                HWMessageBox.Show(this, $"发生异常：{ex.Message}");
                            }
                        }
                        else
                        {
                            SerialPort serialPort = new SerialPort(portName, baudRateValue,
                                CommonHelper.GetEnumByRealValue(parityValue, Parity.None), dataBitValue,
                                CommonHelper.GetEnumByRealValue(stopBitValue, StopBits.One));
                            try
                            {
                                serialPort.Open();
                                serialPort.Write("G1\r");
                                int length = 0;
                                for (var i = 0; i < 3; i++)
                                {
                                    System.Threading.Thread.Sleep(1);
                                    length = serialPort.BytesToRead;
                                    if (length > 0)
                                    {
                                        break;
                                    }
                                    System.Threading.Thread.Sleep(1000);
                                }
                                if (length > 0)
                                {
                                    byte[] buffer = new byte[length];
                                    serialPort.Read(buffer, 0, length);
                                    string content = CommonHelper.RemoveEnterString(Encoding.UTF8.GetString(buffer));
                                    HWMessageBox.Show(this, $"结果：{content}");
                                }
                                else
                                {
                                    HWMessageBox.Show(this, "通讯异常");
                                }
                            }
                            catch (Exception ex)
                            {
                                HWMessageBox.Show(this, $"发生异常：{ex.Message}");
                            }
                            finally
                            {
                                if (serialPort != null && serialPort.IsOpen)
                                {
                                    serialPort.Close();
                                    serialPort = null;
                                }
                            }
                        }
                    }
                }
                else
                {
                    HWMessageBox.Show(this, "名称有误");
                }
            }
            else
            {
                HWMessageBox.Show(this, "请先选中记录");
            }
            CommonHelper.CloseWaiting();
        }
        private void buttonMaxSize_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                this.WindowState = FormWindowState.Normal;
            }
            else
            {
                this.WindowState = FormWindowState.Maximized;
            }
        }
        private void dataGridViewTcp_SelectionChanged(object sender, EventArgs e)
        {
            if (!this.mIsFirstTimeSelected)
            {
                SaveModules();
                int selectedRowIndex = this.dataGridViewTcp.SelectedCells == null || this.dataGridViewTcp.SelectedCells.Count == 0 ? -1 : this.dataGridViewTcp.SelectedCells[0].RowIndex;
                if (selectedRowIndex != -1)
                {
                    DataGridViewRow row = this.dataGridViewTcp.Rows[selectedRowIndex];
                    var name = CommonHelper.GetCellStringValue(row, "Name");
                    var ip = CommonHelper.GetCellStringValue(row, "TcpIP");
                    var port = CommonHelper.GetCellStringValue(row, "TcpPort");
                    var statusAddress = CommonHelper.GetCellStringValue(row, "Status");
                    IPAddress ipValue = null;
                    int portValue = 502;
                    HeliumTcpParam p = new HeliumTcpParam()
                    {
                        Remark = name,
                        ServerIP = IPAddress.TryParse(ip, out ipValue) ? ipValue.ToString() : "",
                        ServerPort = int.TryParse(port, out portValue) ? portValue : 0,
                        StatusAddress = statusAddress,
                    };
                    if (row.Tag != null)
                    {
                        HeliumTcpParam cp = row.Tag as HeliumTcpParam;
                        p.PLCEntities = cp.PLCEntities;
                    }
                    row.Tag = p;
                    ShowModules(p.PLCEntities);
                    this.mSerialLastSelectedRowIndex = -1;
                    this.mTcpLastSelectedRowIndex = selectedRowIndex;
                }
            }
            this.mIsFirstTimeSelected = false;
        }
        private void SaveModules()
        {
            Console.WriteLine($"SaveModule, tcp：{this.mTcpLastSelectedRowIndex}，serial：{this.mSerialLastSelectedRowIndex}");
            List<HeliumPLCEntity> list = new List<HeliumPLCEntity>();
            if (this.dataGridViewModules.Rows != null && this.dataGridViewModules.Rows.Count > 0)
            {
                foreach (DataGridViewRow row in this.dataGridViewModules.Rows)
                {
                    var p = new HeliumPLCEntity()
                    {
                        Remark = CommonHelper.GetCellStringValue(row, "remarkModuleColumn"),
                        TriggerBackgroudAddress = CommonHelper.GetCellStringValue(row, "triggerBackgroudModuleColumn"),
                        BackgroudJudgeAddress = CommonHelper.GetCellStringValue(row, "backgroudJudgeModuleColumn"),
                        TriggerHeliumAddress = CommonHelper.GetCellStringValue(row, "triggerHeliumModuleColumn"),
                        HeliumJudgeAddress = CommonHelper.GetCellStringValue(row, "heliumJudgeModuleColumn"),
                        LeakValueAddress = CommonHelper.GetCellStringValue(row, "leakValueModuleColumn"),
                        PressValueAddress = CommonHelper.GetCellStringValue(row, "pressValueModuleColumn"),
                        HeliumTimesAddress = CommonHelper.GetCellStringValue(row, "heliumTimesModuleColumn"),
                        HeliumResultAddress = CommonHelper.GetCellStringValue(row, "heliumResultModuleColumn"),
                        ReadPermitAddress = CommonHelper.GetCellStringValue(row, "readPermitModuleColumn"),
                    };
                    if (!string.IsNullOrWhiteSpace(p.Remark) && (!string.IsNullOrWhiteSpace(p.TriggerBackgroudAddress) || !string.IsNullOrWhiteSpace(p.TriggerHeliumAddress)))
                    {
                        list.Add(p);
                    }
                }
            }
            if (this.mTcpLastSelectedRowIndex != -1)
            {
                var tcpRow = this.dataGridViewTcp.Rows[this.mTcpLastSelectedRowIndex];
                if (tcpRow != null && tcpRow.Tag != null)
                {
                    HeliumTcpParam t = tcpRow.Tag as HeliumTcpParam;
                    t.PLCEntities = list;
                    tcpRow.Tag = t;
                }
            }
            else if (this.mSerialLastSelectedRowIndex != -1)
            {
                var serialRow = this.dataGridViewSerial.Rows[this.mSerialLastSelectedRowIndex];
                if (serialRow != null && serialRow.Tag != null)
                {
                    HeliumComParam t = serialRow.Tag as HeliumComParam;
                    t.PLCEntities = list;
                    serialRow.Tag = t;
                }
            }
        }

        private void dataGridViewSerial_SelectionChanged(object sender, EventArgs e)
        {
            if (!this.mIsFirstTimeSelected)
            {
                SaveModules();
                int selectedRowIndex = this.dataGridViewSerial.SelectedCells == null || this.dataGridViewSerial.SelectedCells.Count == 0 ? -1 : this.dataGridViewSerial.SelectedCells[0].RowIndex;
                if (selectedRowIndex != -1)
                {
                    DataGridViewRow row = this.dataGridViewSerial.Rows[selectedRowIndex];
                    var name = CommonHelper.GetCellStringValue(row, "Name");
                    var statusAddress = CommonHelper.GetCellStringValue(row, "Status");
                    var portName = CommonHelper.GetCellStringValue(row, "PortName");
                    var baudRate = CommonHelper.GetCellStringValue(row, "BaudRate");
                    var parity = CommonHelper.GetCellStringValue(row, "Parity");
                    var dataBit = CommonHelper.GetCellStringValue(row, "DataBit");
                    var stopBit = CommonHelper.GetCellStringValue(row, "StopBit");
                    int baudRateValue = int.Parse(baudRate);
                    int parityValue = int.Parse(parity);
                    int dataBitValue = int.Parse(dataBit);
                    int stopBitValue = int.Parse(stopBit);
                    HeliumComParam p = new HeliumComParam()
                    {
                        Remark = name,
                        PortName = portName,
                        BaudRate = baudRateValue,
                        DataBits = dataBitValue,
                        Parity = parityValue,
                        StopBits = stopBitValue,
                        StatusAddress = statusAddress,
                    };
                    if (row.Tag != null)
                    {
                        HeliumComParam cp = row.Tag as HeliumComParam;
                        p.PLCEntities = cp.PLCEntities;
                    }
                    row.Tag = p;
                    ShowModules(p.PLCEntities);
                    this.mTcpLastSelectedRowIndex = -1;
                    this.mSerialLastSelectedRowIndex = selectedRowIndex;
                }
            }
            this.mIsFirstTimeSelected = false;
        }
        private void ShowModules(List<HeliumPLCEntity> list)
        {
            this.dataGridViewModules.Rows.Clear();
            if (list != null && list.Count > 0)
            {
                foreach (var l in list)
                {
                    int index = this.dataGridViewModules.Rows.Add(1);
                    DataGridViewRow newRow = this.dataGridViewModules.Rows[index];
                    newRow.Cells["remarkModuleColumn"].Value = l.Remark;
                    newRow.Cells["triggerBackgroudModuleColumn"].Value = l.TriggerBackgroudAddress;
                    newRow.Cells["backgroudJudgeModuleColumn"].Value = l.BackgroudJudgeAddress;
                    newRow.Cells["triggerHeliumModuleColumn"].Value = l.TriggerHeliumAddress;
                    newRow.Cells["heliumJudgeModuleColumn"].Value = l.HeliumJudgeAddress;
                    newRow.Cells["leakValueModuleColumn"].Value = l.LeakValueAddress;
                    newRow.Cells["pressValueModuleColumn"].Value = l.PressValueAddress;
                    newRow.Cells["heliumTimesModuleColumn"].Value = l.HeliumTimesAddress;
                    newRow.Cells["heliumResultModuleColumn"].Value = l.HeliumResultAddress;
                    newRow.Cells["readPermitModuleColumn"].Value = l.ReadPermitAddress;
                }
            }
        }
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = tabControl1.SelectedIndex;
            if (index == 0)
            {
                this.dataGridViewTcp.Rows[0].Cells[0].Selected = true;
            }
            else if (index == 1)
            {
                this.dataGridViewSerial.Rows[0].Cells[0].Selected = true;
            }
        }
        private void FormHelium_Shown(object sender, EventArgs e)
        {
        }
        private void FormHelium_FormClosing(object sender, FormClosingEventArgs e)
        {
        }
    }
}
